package tacos.messing.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tacos.domain.Order;
import tacos.messing.OrderMessageService;


@Service
public class RabbitmqMessagingService implements OrderMessageService {

    private RabbitTemplate rabbit;

    @Autowired
    public RabbitmqMessagingService(RabbitTemplate rabbit) {
        this.rabbit = rabbit;
    }

    @Override
    public void sendOrder(Order order) {
        // "" 代表默认的 Default交换机
        rabbit.convertAndSend("", "yuki", order, this::addOrderSource);
    }

    //    @Override
//    public void sendOrder(Order order) {
//        // 获取消息转换器
//        MessageConverter messageConverter = rabbit.getMessageConverter();
//        // 通过MessageProperties 提供消息属性
//        MessageProperties messageProperties = new MessageProperties();
//        /// 转换消息
//        Message message = messageConverter.toMessage(order, messageProperties);
//        // 发送消息(这里只指定了rootingKey,会先使用yml中的exchange,如果yml中没有配置，则会使用默认的Default exchange)
////        rabbit.send("tacocloud.order",message);
//        rabbit.send("yuki","yuki",message);
//    }
    private Message addOrderSource(Message message) {
        /**
         * 因为可能在多个地方的convertAndSend方法中都添加请求头，所有最好使用方法引用的形式
         */
        MessageProperties messageProperties = message.getMessageProperties();
        messageProperties.setHeader("X_ORDER_SOURCE", "WEB");
        messageProperties.setContentType("application/json");
        return message;
    }

}
